import { Component, Vue } from 'vue-property-decorator'
import Styles from './index.less'
import OperationCol from '@/components/OperationCol'
import service from '@/lib/service'
import { ElForm } from 'element-ui/types/form'
import { applyTypes, formatStatus } from '@/lib/sealFormat'
import SelectDialog from '@/components/selectDialog'
import { ICardOption } from '@/components/selectDialog/selectCard'
import TableEmpty from '@/components/tableEmpty'

interface TableData {
  id: string
  orgName: string
  licenseNumber: string
  parentOrgName: string
  applyTime: string
  status: number
}

const selectDialogOptions: ICardOption[] = [
  {
    icon: 'iconchuangjianzuzhijigou-default1',
    title: '创建组织机构',
    description: '组织机构不存在，需要创建新的组织机构',
  },
  {
    icon: 'iconjigouxinxigengxin-default1',
    title: '机构信息更新',
    description: '机构信息（如机构单位名称、证照号码等）错误',
  },
]

@Component({})
export default class OrganizationManagement extends Vue {
  tableData: TableData[] = []

  private ruleForm: any = {
    applyCode: '',
    daterange: '',
    status: [],
  }
  private pagesObj: any = {
    index: 1,
    size: 10,
    total: 0,
  }

  loading: boolean = false

  selectDialogVisible: boolean = false

  protected render() {
    return (
      <div class={Styles.organizationManagementView}>
        <el-form {...{ props: { model: this.ruleForm } }} ref="elform">
          <el-form-item label="申请编号">
            <el-input size="mini" v-model={this.ruleForm.applyCode} />
          </el-form-item>
          <el-form-item label="提交时间">
            <el-date-picker
              v-model={this.ruleForm.daterange}
              type="daterange"
              size="mini"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item label="申请状态">
            <el-select
              v-model={this.ruleForm.status}
              placeholder="默认全部"
              size="mini"
              multiple
              collapse-tags
            >
              <el-option label="待审核" value={0} />
              <el-option label="审核通过" value={1} />
              <el-option label="已退回" value={2} />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" type="primary" onClick={this.searchData}>
              搜索
            </el-button>
            <el-button size="mini" onClick={this.resetForm}>
              重置
            </el-button>
          </el-form-item>
        </el-form>

        <p class="pt5">
          <el-button
            class="medium bg-color-blue"
            onClick={() => {
              this.selectDialogVisible = true
            }}
          >
            申请组织机构
          </el-button>
        </p>

        <el-table data={this.tableData} v-loading={this.loading}>
          <TableEmpty
            v-show={!this.loading}
            slot="empty"
            msg="暂无匹配的组织机构更新申请记录"
          >
            <el-button type="primary" onClick={this.toApply}>
              前往申请组织机构
            </el-button>
          </TableEmpty>
          <el-table-column
            prop="applyCode"
            label="申请编号"
            show-overflow-tooltip
          />
          <el-table-column
            prop="orgName"
            label="机构名称"
            show-overflow-tooltip
          />
          <el-table-column prop="area" label="所在区域" show-overflow-tooltip />
          <el-table-column
            prop="licenseNumber"
            label="证照号码"
            show-overflow-tooltip
          />
          <el-table-column
            prop="parentOrgName"
            label="上级机构名称"
            show-overflow-tooltip
          />
          <el-table-column
            prop="applyTime"
            label="提交时间"
            show-overflow-tooltip
          />
          <el-table-column
            prop="status"
            label="申请类型"
            show-overflow-tooltip
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return formatStatus(applyTypes, scope.row.applyType)
                },
              },
            }}
          />
          <el-table-column
            prop="status"
            label="申请状态"
            show-overflow-tooltip
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return this.formatStatus(scope.row.status)
                },
              },
            }}
          />
          <el-table-column
            prop="id"
            label="操作"
            width="200"
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return (
                    <OperationCol
                      operations={this.getgetOperations}
                      showNum={2}
                      row={scope.row}
                      index={scope.$index}
                    />
                  )
                },
              },
            }}
          />
        </el-table>
        {this.tableData && this.tableData.length > 0 && (
          <el-pagination
            style={{ display: this.pagesObj.total ? 'block' : 'none' }}
            onSize-change={this.handleSizeChange}
            onCurrent-change={this.handleCurrentChange}
            current-page={this.pagesObj.index}
            page-sizes={[10, 20, 30]}
            page-size={this.pagesObj.size}
            layout="total, sizes, prev, pager, next, jumper"
            total={this.pagesObj.total}
            pager-count={5}
          />
        )}
        <SelectDialog
          dialogVisible={this.selectDialogVisible}
          {...{
            on: {
              'update:dialogVisible': this.setDialogVisible,
            },
          }}
          options={selectDialogOptions}
          onselected={this.handleDialogSelected}
          title="请选择机构更新类型"
        />
      </div>
    )
  }

  private mounted() {
    this.getTableList()
  }

  private setDialogVisible(v: boolean) {
    this.selectDialogVisible = v
  }

  private handleDialogSelected(v: ICardOption) {
    if (v.title === selectDialogOptions[0].title) {
      // 创建组织机构
      this.gotoApply()
    } else if (v.title === selectDialogOptions[1].title) {
      // 机构信息更新
      this.gotoUpdate()
    }
    this.selectDialogVisible = false
  }

  private handleSizeChange(val: number) {
    this.pagesObj.index = 1
    this.pagesObj.size = val
    this.getTableList()
  }

  private handleCurrentChange(val: number) {
    this.pagesObj.index = val
    this.getTableList()
  }

  toApply() {
    this.selectDialogVisible = true
  }

  private async getTableList() {
    let applyTimeStart: any = ''
    let applyTimeEnd: any = ''

    if (Array.isArray(this.ruleForm.daterange)) {
      ;[applyTimeStart, applyTimeEnd] = this.ruleForm.daterange

      applyTimeStart = new Date(applyTimeStart)
      applyTimeEnd = new Date(applyTimeEnd)

      applyTimeStart.setDate(applyTimeStart.getDate() + 1)
      applyTimeEnd.setDate(applyTimeEnd.getDate() + 1)

      applyTimeStart = applyTimeStart.toISOString().replace(/T.+/, 'T00:00:00')
      applyTimeEnd = applyTimeEnd.toISOString().replace(/T.+/, 'T23:59:59')
    }
    this.loading = true
    await this.$nextTick()
    await service({
      url: '/seal/rest/organize/listMyNewOrganizationApply',
      method: 'POST',
      body: {
        ...this.ruleForm,
        applyTimeStart,
        applyTimeEnd,
        pageIndex: this.pagesObj.index,
        pageSize: this.pagesObj.size,
      },
    }).then(res => {
      this.tableData = res.data.list
      this.pagesObj.total = res.data.total
    })
    await this.$nextTick()
    this.loading = false
  }

  get getgetOperations() {
    return [
      {
        id: 0,
        text: '详情',
        onClick: (index: number, rows: any) => {
          this.$router.push({
            name: 'organizationDetail',
            params: {
              type: this.$route.name || '',
            },
            query: { id: rows.id },
          })
        },
      },
    ]
  }

  private gotoApply() {
    this.$router.push({
      name: 'organizationApply',
      params: {
        type: this.$route.name || '',
      },
    })
  }

  private gotoUpdate() {
    this.$router.push({
      name: 'organizeUpdate',
      params: {
        type: this.$route.name || '',
      },
    })
  }

  private resetForm() {
    this.$refs.elform &&
      (this.$refs.elform as ElForm) &&
      (this.$refs.elform as ElForm).resetFields()

    this.ruleForm = {
      applyCode: '',
      daterange: '',
      status: [],
    }
    this.searchData()
  }

  private searchData() {
    this.pagesObj.index = 1
    this.getTableList()
  }

  /**
   * 生成状态标签
   * @param status 状态码
   */
  private formatStatus(status: number) {
    const applyStatus: any = {
      0: {
        label: '待审核',
        color: '#5B9BD5',
      },
      1: {
        label: '审核通过',
        color: '#52C41A',
      },
      2: {
        label: '已退回',
        color: '#F5222D',
      },
    }

    return (
      <div>
        <i
          style={{
            display: 'inline-block',
            backgroundColor: applyStatus[status].color,
            width: '10px',
            height: '10px',
            borderRadius: '100%',
            margin: '0 5px 0 0',
          }}
        />
        <span>{applyStatus[status].label}</span>
      </div>
    )
  }
}
